package com.wkcto.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wkcto.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * 认证失败时调用
 */
@Component
public class MyFailurHandler implements AuthenticationFailureHandler {
    /**
     * 参数:
     * @param httpServletRequest 请求
     * @param httpServletResponse 应答
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //当框架验证用户信息失败时执行的方法
        httpServletResponse.setContentType("text/json;charset=utf-8");
//        PrintWriter writer = httpServletResponse.getWriter();
//        writer.println("{\"msg\":\"登录失败(用户名或密码有误)!\"}");
//        writer.flush();
//        writer.close();

        Result result = new Result();
        result.setCode(1);
        result.setError(1001);
        result.setMsg("登录失败!");


        OutputStream outputStream = httpServletResponse.getOutputStream();

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(outputStream, result);

        outputStream.flush();



    }
}
